<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\common\logic;

use app\common\model\UserAccount;
use app\common\model\UserAccountLog;
use app\common\model\UserKingInvestment;
use think\Db;

/**
 * Recharge逻辑
 */
class Financial extends LogicBase
{
    

    
    /**
     * 获取游戏币总转换列表
     */
    public function get_trade_list($data = [], $field = 'a.*,c.username ', $order = '', $paginate = DB_LIST_ROWS)
    {
        


        $where = $where1 = [];
        if (!empty($data['date1']) && !empty($data['date2'])) {
            $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), strtotime($data['date2'] . ' 23:59:59')]];
        }
        if (!empty($data['search_data'])) {
            $where['a.user_id|c.username|c.mobile'] = $data['search_data'];

        }
        if (!empty($data['investment_type'])) {
            $where['a.investment_type'] = $data['investment_type'];
        }

        $where['a.status'] =1;
        if (!empty($data['king_id'])) {
            $where['a.king_id'] = $data['king_id'];
        }
        if (!empty($data['user_investment_id'])) {
            $where['a.user_investment_id'] = $data['user_investment_id'];
        }

        $list =  $this->modelUserKingInvestment->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->field($field)->where($where)->order($order)->paginate($paginate, false, ['query' => $data]);
        $count =  $this->modelUserKingInvestment->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->field($field)->where($where)->count();

        return ['count'=>$count,'list'=>$list];



    }

    /***
     * 委托撤单
     */
    public function  cancel_entrust($data){
        $time=time();


        Db::startTrans();
        try{
            $info=$this->modelUserKingInvestment->where(['id'=>$data['id']])->lock(true)->find();
            $user_account=UserAccount::check(['user_id'=>$info['user_id'],'wallet_id'=>3],false);


            $total=$info['money'];

            //修改状态为解除中
            UserKingInvestment::where(['id'=>$info['id']])->update(['state'=>2,'update_time'=>$time]);


            $user_account->balance+=$total;
            $user_account->freeze_balance-=$total;
            $user_account->save();
            //写入资金流水
            UserAccountLog::create([
                'user_id'=>$user_account['user_id'],
                'number'=>$total,
                'wallet_id'=>$user_account['wallet_id'],
                'before_blance'=>$user_account->balance-$total,
                'after_blance'=>$user_account->balance,
                'is_add'=>1,
                'type'=>8
            ]);
            $info->kinguser->surplus_money-=$total;
            $info->kinguser->save();
            $info->king->surplus_total_money-=$total;
            $info->king->save();
            $member=\app\common\model\Member::get($info['user_id']);

            //等级降级
            $member->lei_money-=$total;
            $member->save();
            $member->downgrade($total);
            Db::commit();
            return [RESULT_SUCCESS, '操作成功']  ;

        }catch (\Exception $e){
            Db::rollback();
            return [RESULT_ERROR, $e->getMessage()];

        }

    }

    /**
     * 获取红利详情列表
     */
    public function get_bonus_list($data = [], $field = 'a.*,c.username ', $order = '', $paginate = DB_LIST_ROWS)
    {



        $where = $where1 = [];
        if (!empty($data['date1']) && !empty($data['date2'])) {
            $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), strtotime($data['date2'] . ' 23:59:59')]];
        }
        if (!empty($data['king_id'])) {
            $where['a.user_king_id'] = $data['king_id'];
        }

        $where['a.status'] =['gt',1];
//        if (!empty($data['game_id'])) {
//            $where['a.game_id'] = $data['game_id'];
//        }



        $list =  $this->modelBonusLog->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->field($field)->where($where)->order($order)->paginate($paginate, false, ['query' => $data]);
        $count =  $this->modelBonusLog->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->field($field)->where($where)->count();


        $ke=$this->modelBonusLog->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->where($where)->sum('number');

        $ke=$ke?$ke:0;

        return ['count'=>$count,'list'=>$list,'ke'=>$ke];



    }

    /**
     * 导出记录
     */
    public function exportTradeList($data, $field = 'a.*,c.username', $order = 'create_time desc, id desc')
    {
        $where = $where1 = [];
        if (!empty($data['date1']) && !empty($data['date2'])) {
            $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), strtotime($data['date2'] . ' 23:59:59')]];
        }
        if (!empty($data['search_data'])) {
            $where1['a.user_id'] = $data['search_data'];
            $where1['c.username'] =$data['search_data'] ;
        }
        if (!empty($data['investment_type'])) {
            $where['a.investment_type'] = $data['investment_type'];
        }

        $where['a.status'] =1;
//        if (!empty($data['game_id'])) {
//            $where['a.game_id'] = $data['game_id'];
//        }

        if (!empty($where1)) {

            $list =  $this->modelUserKingInvestment->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->field($field)->where($where)->where(function ($q)use($where1){
                $q->whereOr($where1);
            })->order($order)->select();


        } else {

            $list =  $this->modelUserKingInvestment->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->field($field)->where($where)->order($order)->select();

        }



        foreach ($list as $k => $v) {
            $list[$k]['k'] = $k+1;
            $list[$k]['king_name'] = $v->investment->king->data['name'];
            $list[$k]['investment_name'] = $v->investment->data['name'];
            $list[$k]['type_name'] = $v->investment_type==1?'心血公式':'赌王投资';
            $list[$k]['investment_bonus'] = $v->investment->bonus;
            $list[$k]['state_text'] = $v->state_text;

        }

        $titles = "序号,ID,用户账号,用户ID,赌王名称,理财类型,理财名称,金额,盈利百分比,已分红金额,状态,购买时间";
        $keys = "k,id,username,user_id,king_name,type_name,investment_name,money,investment_bonus,profit,state_text,create_time";
        action_log('导出', '导出理财记录');
        export_excel($titles, $keys, $list, '理财记录');


    }





    /**
     * 文章信息编辑
     */
    public function LevelEdit($data = [])
    {


//        dd($data);
        $url = url('level_list');

        // empty($data['id']) && $data['member_id'] = MEMBER_ID;

        $shares= [];

        $share=[
            'level'=>$data['share_first'][0],
        ];
        $datas=[];

        for ($i=0;$i<$data['share_first'][0];$i++){
                 $a=$i+1;
                 if(isset($data['share'.$a][0])){

                     $datas[]=$data['share'.$a][0];

                 }
        }

        $share['reward']=$datas;
        $shares[]=$share;
        $data['share_json']=json_encode($shares);


//        dd($data);
        $result = $this->modelUserLevel->setInfo($data);
        $handle_text = empty($data['id']) ? '新增' : '编辑';

        $result && action_log($handle_text, '等级' . $handle_text . '，level_name：' . $data['level_name']);

        return $result ? [RESULT_SUCCESS, '等级操作成功', $url] : [RESULT_ERROR,
            '编辑失败'];
    }





    /**


    /**
     * 兑换游戏币审核
     */
    public function setStatus($data=[])
    {

        $info = $this->modelUserKingInvestment->getInfo(['id' => $data['id']]);
        Db::startTrans();
        try {


            if ($data['state'] == 1) {
                //审核通过
                    return [RESULT_ERROR, '暂未开放该功能'];



            }else{
                //账户变动
                $useracount = $this->modelUserAccount->where(['wallet_id' => $info['form_wallet_id'], 'user_id' => $info['user_id']])->lock(true)->find();
                $useracount->balance += $info['number'];
                $useracount->save();
                if($info['type']==5){
                    $data['before_available_balance'] = $useracount->balance - $info['number'];
                    $data['after_available_balance'] = $useracount->balance;
                }

                if($info['type']==6){
                    $data['before_against_balance'] = $useracount->balance - $info['number'];
                    $data['after_against_balance'] = $useracount->balance;
                }


                //写入流水
                UserAccountLog::create([
                    'user_id' => $info['user_id'],
                    'number' => $info['number'],
                    'wallet_id' =>  $info['form_wallet_id'],
                    'before_blance' => $useracount->balance - $info['number'],
                    'after_blance' => $useracount->balance,
                    'is_add' => 1,
                    'type' => 2
                ]);
            }

            $result = $this->modelUserKingInvestment->setInfo($data);
            $msg = $data['state'] == 1 ? '审核成功' : '拒绝审核';
            $result && action_log('兑换游戏币审核审核', $msg);
            Db::commit();
            return $result ? [RESULT_SUCCESS, '审核成功'] : [RESULT_ERROR, '审核失败'];

        } catch (\Exception $e) {
            Db::rollback();
            return [RESULT_ERROR, $e->getMessage()];
        }
    }


    /**
     * 获取游戏下注记录列表
     */
    public function bets_log($data = [], $field = 'a.*,c.username ', $order = '', $paginate = DB_LIST_ROWS)
    {



        $where = $where1 = [];
        if (!empty($data['date1']) && !empty($data['date2'])) {
            $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), strtotime($data['date2'] . ' 23:59:59')]];
        }
        if (!empty($data['search_data'])) {
            $where1['a.user_id'] = $data['search_data'];
            $where1['c.username'] =$data['search_data'] ;
        }

//        if (!empty($data['game_id'])) {
//            $where['a.game_id'] = $data['game_id'];
//        }



        if (!empty($where1)) {

            $list =  $this->modelBetsLog->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->field($field)->where($where)->where(function ($q)use($where1){
                $q->whereOr($where1);
            })->order($order)->paginate($paginate, false, ['query' => $data]);
            $count =  $this->modelBetsLog->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->field($field)->where($where)->where(function ($q)use($where1){
                $q->whereOr($where1);
            })->count();

        } else {

            $list =  $this->modelBetsLog->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->field($field)->where($where)->order($order)->paginate($paginate, false, ['query' => $data]);
            $count =  $this->modelBetsLog->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->field($field)->where($where)->count();
        }



        $ke=$this->modelBetsLog->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->where($where)->sum('number');

        $ke=$ke?$ke:0;

        return ['count'=>$count,'list'=>$list,'ke'=>$ke];



    }


    /**
     * 导出记录
     */
    public function exportBetsList($data, $field = 'a.*,c.username', $order = 'create_time desc, id desc')
    {

        $where = $where1 = [];
        if (!empty($data['date1']) && !empty($data['date2'])) {
            $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), strtotime($data['date2'] . ' 23:59:59')]];
        }
        if (!empty($data['search_data'])) {
            $where1['a.user_id'] = $data['search_data'];
            $where1['c.username'] =$data['search_data'] ;
        }
//        if (!empty($data['game_id'])) {
//            $where['a.game_id'] = $data['game_id'];
//        }

        if (!empty($where1)) {

            $list =  $this->modelBetsLog->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->field($field)->where($where)->where(function ($q)use($where1){
                $q->whereOr($where1);
            })->order($order)->select();


        } else {

            $list =  $this->modelBetsLog->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->field($field)->where($where)->order($order)->select();

        }



        foreach ($list as $k => $v) {
            $list[$k]['k'] = $k+1;


        }

        $titles = "序号,ID,用户账号,用户ID,金额,下注时间";
        $keys = "k,id,username,user_id,number,create_time";
        action_log('导出', '导出下注记录');
        export_excel($titles, $keys, $list, '下注记录');


    }











}
